package com.han.yuhannews.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.han.yuhannews.adapter.CategoryAdapter;
import com.han.yuhannews.model.Category;
import com.han.yuhannews.util.DensityUtil;
import com.han.yuhannews.util.StringUtil;

import com.han.yuhannews.R;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MainActivity extends Activity {
	private int mCOLUMNWIDTHDIP = 0;
	private int mFlingVelocityDip = 0;
	private int mCid = 1;
	private String mCategoryTitle = "焦点";
	private final int COLUMNWIDTHPX = 55;
	private final int FLINGVELOCITYPX = 800;
	private final int NEWSCOUNT = 5;

	private ListView mNewsList;
	private Button mTitleBarRefresh;
	private ProgressBar mLoadnewsProgress;
	private Button mLoadMoreBtn;
	private ArrayList<HashMap<String, Object>> mNewsData; // 定义为ArrayList就可以在intent中传递
	private SimpleAdapter mNewsListAdapter;
	private LayoutInflater mInflater;
	private ProgressDialog pDialog;
	private AlertDialog.Builder alertDialog;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mNewsData = new ArrayList<HashMap<String, Object>>();
		mTitleBarRefresh = (Button) findViewById(R.id.titlebar_refresh);
		mTitleBarRefresh.setOnClickListener(loadMoreListener);
		mLoadnewsProgress = (ProgressBar) findViewById(R.id.loadnews_progress);
		mNewsList = (ListView) findViewById(R.id.news_list);
		alertDialog=new AlertDialog.Builder(MainActivity.this);
		mInflater = getLayoutInflater();
		initCategory();
		initListViewItem();
		
	}

	/*
	 * 初始化listView的适配器
	 */
	private void initListViewItem() {
		mNewsListAdapter = new SimpleAdapter(this, mNewsData,
				R.layout.newslist_item, new String[] { "newslist_item_title",
						"newslist_item_digest", "newslist_item_source",
						"newslist_item_ptime" }, new int[] {
						R.id.newslist_item_title, R.id.newslist_item_digest,
						R.id.newslist_item_source, R.id.newslist_item_ptime });
		View footView = mInflater.inflate(R.layout.listview_item_loadmore, null);
		mNewsList.addFooterView(footView);
		mNewsList.setAdapter(mNewsListAdapter);
		// 第一次自动获取服务器新闻
		loginAsynchttp(1, 0, true, mNewsData);

		mNewsList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 传递数据
				Intent intent = new Intent(MainActivity.this,
						NewsDetailsActivity.class);
				intent.putExtra("categoryTitle", mCategoryTitle);
				intent.putExtra("position", position);
				intent.putExtra("newsData", mNewsData);
				startActivity(intent);

			}
		});
		Button mLoadMoreBtn = (Button) findViewById(R.id.loadmore_btn);
		mLoadMoreBtn.setOnClickListener(loadMoreListener);

	}

	/*
	 * 初始化新闻分类栏
	 */
	private void initCategory() {
		// 从res中的array获取新闻分类
		String[] categoryArray = getResources().getStringArray(
				R.array.categories);
		// 把新闻分类保存到List中
		final List<HashMap<String, Category>> categories = new ArrayList<HashMap<String, Category>>();
		// 分割新闻分类中的字符串和|
		for (int i = 0; i < categoryArray.length; i++) {
			String[] temp = categoryArray[i].split("[|]");
			// 将Stirng数组分割后，左边是cid新闻类型代号，右边是类型名称，按顺序保存在temp数组中，所以判断分割后temp【】长度为2就是正确的
			if (temp.length == 2) {
				int cid = StringUtil.String2Int(temp[0]);
				String title = temp[1];
				Category type = new Category(cid, title);
				HashMap<String, Category> hashMap = new HashMap<String, Category>();
				hashMap.put("category_title", type);
				categories.add(hashMap);

			}
		}

		CategoryAdapter categoryAdapter = new CategoryAdapter(this, categories,
				R.layout.category_title, new String[] { "category_title" },
				new int[] { R.id.category_title });
		// 动态设置GridView的布局
		GridView category = new GridView(this);
		mCOLUMNWIDTHDIP = DensityUtil.px2dip(this, COLUMNWIDTHPX) + 90; // 调用工具类的方法将px转换为dip
		mFlingVelocityDip = DensityUtil.px2dip(this, FLINGVELOCITYPX) + 90;
		category.setColumnWidth(mCOLUMNWIDTHDIP);
		category.setNumColumns(GridView.AUTO_FIT);
		category.setGravity(Gravity.CENTER);
		category.setSelector(new ColorDrawable(Color.TRANSPARENT));
		int width = mCOLUMNWIDTHDIP * categories.size();
		LayoutParams params = new LayoutParams(width, LayoutParams.WRAP_CONTENT);
		category.setLayoutParams(params);
		category.setAdapter(categoryAdapter);
		// 将gridview设置到linearlayout中
		LinearLayout categorylayout = (LinearLayout) findViewById(R.id.category_layout);
		categorylayout.addView(category);
		category.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				TextView categoryTitle = null;
				for (int i = 0; i < parent.getChildCount(); i++) {
					// 遍历所有的项且改变所有字体颜色
					categoryTitle = (TextView) parent.getChildAt(i);
					categoryTitle.setTextColor(0XFFADB2AD);
					categoryTitle.setBackgroundDrawable(null); // 并且清除背景
				}
				// 再改变点击项的字体颜色
				categoryTitle = (TextView) view;
				categoryTitle.setTextColor(0XFFFFFFFF);
				categoryTitle
						.setBackgroundResource(R.drawable.categorybar_item_background);
				mCid = categories.get(position).get("category_title").getCid();
				mCategoryTitle = categories.get(position).get("category_title")
						.getTitle();
				Log.i("cid==========", String.valueOf(mCid));
				
				loginAsynchttp(mCid,0, true, mNewsData);
			}
		});

		// 设置新闻栏可以横向滑动
		final HorizontalScrollView categoryScrollview = (HorizontalScrollView) findViewById(R.id.category_scrollview);
		Button button = (Button) findViewById(R.id.category_arrow_right);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				switch (view.getId()) {
				case R.id.category_arrow_right:
					categoryScrollview.fling(mFlingVelocityDip);
					break;
				}
			}
		});

	}

	/*
	 * 从服务器获取新闻
	 */

	private OnClickListener loadMoreListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			
			switch (v.getId()) {
			case R.id.loadmore_btn:
				loginAsynchttp(mCid, mNewsData.size(), false, mNewsData);
				
				break;

			case R.id.titlebar_refresh:

				loginAsynchttp(mCid, 0, true, mNewsData);
				break;
			}

		}
	};

	
	
	/**
	 * 异步任务处理网络请求
	 * @param startnid 起始新闻条数
	 * @param cid 新闻分类编号
	 * @param firstTimes 是否第一次加载
	 * @param newsList 适配器的数据集合
	 */
	public void loginAsynchttp(int cid, int startnid, final Boolean firstTimes,
			final List<HashMap<String, Object>> newsList){
		if (firstTimes) {
			// 如果是第一次，则清空集合里数据,那么ListView绑定的数据发生了变化，就必须要更新适配器
			newsList.clear();
			mNewsListAdapter.notifyDataSetChanged();
		}
		AsyncHttpClient client =new AsyncHttpClient();
		String url = "http://172.16.5.243:8080/web/getSpecifyCategoryNews";
		RequestParams params = new RequestParams();
		params.put("count", NEWSCOUNT);
		params.put("startnid", startnid);
		params.put("cid",cid);
		client.setTimeout(6000);
		pDialog =ProgressDialog.show(this, "请稍等", "数据加载中",true,true);
		client.get(url, params,new AsyncHttpResponseHandler() {
			
			//此方法已经返回主线程中了，可以进行UI的更新操作
			@Override
			public void onSuccess(int  statusCode, Header[] headers, byte[] responseBody) {
				pDialog.dismiss();
				String retStr =new String(responseBody);
				try {
					JSONObject jsonObject = new JSONObject(retStr);
					int retCode = jsonObject.getInt("ret");
					if (retCode == 0) {
						JSONObject dataObject = jsonObject.getJSONObject("data");
						int totalNum = dataObject.getInt("totalnum");
						if (totalNum > 0) {
							JSONArray newslistArray = dataObject.optJSONArray("newslist");
							for (int i = 0; i < newslistArray.length(); i++) {
								JSONObject newsObject = newslistArray.getJSONObject(i);
								HashMap<String, Object> hashMap = new HashMap<String, Object>();
								hashMap.put("nid", newsObject.getInt("nid"));
								// put到hashMap中的key一定要和适配器定义的一致，否则无法显示
								hashMap.put("newslist_item_title",
										newsObject.getString("title"));
								hashMap.put("newslist_item_digest",
										newsObject.getString("digest"));
								hashMap.put("newslist_item_source",
										newsObject.getString("source"));
								hashMap.put("newslist_item_ptime",
										newsObject.getString("ptime"));
								hashMap.put("newslist_item_comments",
										newsObject.getString("commentcount"));
								newsList.add(hashMap);
								//因为listView的数据已经更新了，所以必须更新适配器
								mNewsListAdapter.notifyDataSetChanged();
							}
						}
						//返回的数目为0
						else {
							if (firstTimes) {
								pDialog.dismiss();
								alertDialog.setTitle("提示窗");
								alertDialog.setMessage("该栏目暂未开放");
								alertDialog.setCancelable(false);
								alertDialog.setNegativeButton("确定", null);
								alertDialog.show();
							} else{
								pDialog.dismiss();
								alertDialog.setTitle("提示窗");
								alertDialog.setMessage("没有更多的新闻了");
								alertDialog.setCancelable(false);
								alertDialog.setNegativeButton("确定", null);
								alertDialog.show();
							}
						}
					}
							}
					
				 catch (JSONException e) {
					e.printStackTrace();
					pDialog.dismiss();
					alertDialog.setTitle("失败");
					alertDialog.setMessage("获取新闻失败");
					alertDialog.setCancelable(false);
					alertDialog.setNegativeButton("确定", null);
					alertDialog.show();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				arg3.printStackTrace();
				pDialog.dismiss();
				alertDialog.setTitle("失败");
				alertDialog.setMessage("网络连接异常");
				alertDialog.setCancelable(false);
				alertDialog.setNegativeButton("确定", null);
				alertDialog.show();
			}
		});
		
		
	}
}
